package com.tiantianyuegou.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tiantianyuegou.R;
import com.tiantianyuegou.adapter.GoodsAdapter;
import com.tiantianyuegou.adapter.RedPageAdapter;
import com.tiantianyuegou.http.ApiDefine;
import com.tiantianyuegou.http.SPHelper;
import com.tiantianyuegou.model.GoodsModel;
import com.tiantianyuegou.model.LocalStoreInfo;
import com.tiantianyuegou.model.TicketModel;
import com.tiantianyuegou.util.LoadingDialog;
import com.tiantianyuegou.util.NetworkUtils;
import com.tiantianyuegou.util.PictureUtil;
import com.tiantianyuegou.util.TimeUtils;
import com.tiantianyuegou.util.ToastUtilsCenter;
import com.tiantianyuegou.util.Tools;
import com.tiantianyuegou.view.HorizontalListView;
import com.tiantianyuegou.view.NoScrollGridView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * 店铺详情
 * Created by huyang on 2016/1/11 0011.
 */
public class StoreDetailActivity extends BaseActivity implements View.OnClickListener {

    private NoScrollGridView grid_stroe;
    private ScrollView scrollView;
    private TextView tv_storename;
    private ImageView iv_store;
    private LoadingDialog loadingDialog;
    private String TAG = "StoreDetailActivity";
    private List<TicketModel> data;
    private List<GoodsModel> goodsData;
    private String ttId;
    private HorizontalListView mListView;
    private GoodsAdapter goodsAdapter;
    private RedPageAdapter mAdapter;
    private Context context;
    private LinearLayout layout_start;//店铺星级
    //private LinearLayout layout_ticket;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_storedetail);
        setTitle(R.string.stroe_detail_title);
       Tools.changeSystemBar(this);
        context = this;
        initViews();
    }

    @Override
    public void findViewByIds() {
//        grid_stroe = (NoScrollGridView) findViewById(R.id.store_goods);
        scrollView = (ScrollView) findViewById(R.id.scrollView);
        tv_storename = (TextView) findViewById(R.id.tv_storename);
        iv_store = (ImageView) findViewById(R.id.iv_store);
//        mListView = (HorizontalListView) findViewById(R.id.list_redpag);
        layout_start= (LinearLayout) findViewById(R.id.linear_start);
        //layout_ticket= (LinearLayout) findViewById(R.id.layout_ticket);
    }

    @Override
    public void initListener() {
        data = new ArrayList<>();
        goodsData = new ArrayList<>();
        loadingDialog = new LoadingDialog(context);
        goodsAdapter=new GoodsAdapter(context);
//        grid_stroe.setAdapter(goodsAdapter);
//        grid_stroe.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                String tpId=goodsData.get(i).getTpId();
//                Intent intent = new Intent(context, GoodsDetailActivity.class);
//                intent.putExtra("tpId",tpId);
//                startActivity(intent);
//            }
//        });
        mAdapter = new RedPageAdapter(this);
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if ("".equals(SPHelper.getTmId())) {
                    Intent intent = new Intent(context, LoginActivity.class);
                    startActivityForResult(intent, 1006);
                } else {
                    getTicket();
                }
            }
        });
    }

    @Override
    public void initData() {
        if (!NetworkUtils.isNetworkAvailable(this)) {
            showMsg("请检查网络");
        }
        Intent intent = getIntent();
        final String tsId = intent.getStringExtra("tsId");

        loadingDialog.showDialog();
        loadingDialog.setMsg("正在加载");

        RequestParams params = new RequestParams();
        params.addBodyParameter("tsId", tsId);
        Log.e(TAG,"-----------tsID="+tsId);
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.STORE_DETAIL, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                loadingDialog.dismiss();
                Log.e(TAG, "onSuccess response.result" +
                        response.result);
                if (TextUtils.isEmpty(response.result)) {
                    showMsg("获取店铺详情失败");
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(response.result);
                        String code = jsonObject.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                            JSONObject detail = jsonObject.getJSONObject("detail");
                            String tsName = detail.getString("tsName");
                            String tsLogo = detail.getString("tsLogo");
                            int tsIntegral = detail.getInt("tsIntegral");
                            //String
                            tv_storename.setText(tsName);
//                            ImageLoader.getInstance().displayImage(tsLogo, iv_store);

                            iv_store.setImageBitmap(PictureUtil.comp(ImageLoader.getInstance().loadImageSync(tsLogo)));
                            LocalStoreInfo info = new LocalStoreInfo();
                            //   tsIntegral*=1000000;
                            if (tsIntegral <= 250) {
                                info.setImgRes(R.mipmap.already_collect);
                                if (tsIntegral < 4) {
                                    info.setStartCount(0);
                                } else if (tsIntegral >= 4 && tsIntegral <= 10) {
                                    info.setStartCount(1);
                                } else if (tsIntegral >= 11 && tsIntegral <= 40) {
                                    info.setStartCount(2);
                                } else if (tsIntegral >= 41 && tsIntegral <= 90) {
                                    info.setStartCount(3);
                                } else if (tsIntegral >= 91 && tsIntegral <= 150) {
                                    info.setStartCount(4);
                                } else if (tsIntegral >= 151 && tsIntegral <= 250) {
                                    info.setStartCount(5);
                                }
                            } else if (tsIntegral > 250 && tsIntegral <= 10000) {
                                info.setImgRes(R.mipmap.zuanshi);
                                if (tsIntegral <= 500) {
                                    info.setStartCount(1);
                                } else if (tsIntegral >= 501 && tsIntegral <= 1000) {
                                    info.setStartCount(2);
                                } else if (tsIntegral >= 1001 && tsIntegral <= 2000) {
                                    info.setStartCount(3);
                                } else if (tsIntegral >= 2001 && tsIntegral <= 5000) {
                                    info.setStartCount(4);
                                } else if (tsIntegral >= 5001 && tsIntegral <= 10000) {
                                    info.setStartCount(5);
                                }
                            } else if (tsIntegral > 10000 && tsIntegral <= 500000) {
                                info.setImgRes(R.mipmap.sh_a2);
                                if (tsIntegral <= 20000) {
                                    info.setStartCount(1);
                                } else if (tsIntegral >= 20001 && tsIntegral <= 50000) {
                                    info.setStartCount(2);
                                } else if (tsIntegral >= 50001 && tsIntegral <= 100000) {
                                    info.setStartCount(3);
                                } else if (tsIntegral >= 100001 && tsIntegral <= 200000) {
                                    info.setStartCount(4);
                                } else if (tsIntegral >= 200001 && tsIntegral <= 500000) {
                                    info.setStartCount(5);
                                }
                            } else if (tsIntegral > 500000 && tsIntegral <= 10000000) {
                                info.setImgRes(R.mipmap.sh_a3);
                                if (tsIntegral <= 1000000) {
                                    info.setStartCount(1);
                                } else if (tsIntegral >= 1000001 && tsIntegral <= 2000000) {
                                    info.setStartCount(2);
                                } else if (tsIntegral >= 2000001 && tsIntegral <= 5000000) {
                                    info.setStartCount(3);
                                } else if (tsIntegral >= 5000001 && tsIntegral <= 10000000) {
                                    info.setStartCount(4);
                                } else if (tsIntegral >= 10000001) {
                                    info.setStartCount(5);
                                }
                            }
                            //动态生成店铺的星级
                            layout_start.removeAllViews();
                            for (int i = 0; i < info.getStartCount(); i++) {
                                ImageView imageView = new ImageView(context);
                                imageView.setPadding(5, 0, 5, 0);
                                imageView.setImageResource(info.getImgRes());
                                layout_start.addView(imageView);
                            }
                            //优惠券
                            JSONArray ticket = jsonObject.getJSONArray("ticket");
                            if (ticket.length() > 0) {
                                data.clear();
                                for (int i = 0; i < ticket.length(); i++) {
                                    JSONObject temp = ticket.getJSONObject(i);
                                    String ttMoney = temp.getString("ttMoney");
                                    String ttStart = temp.getString("ttStart");
                                    String ttEnd = temp.getString("ttEnd");
                                    String ttTop = temp.getString("ttTop");
                                    ttId = temp.getString("ttId");
                                    TicketModel model = new TicketModel();
                                    Double price= Double.valueOf(ttMoney);
                                    model.setTtMoney(new DecimalFormat("0").format(price));
                                    Double top= Double.valueOf(ttTop);
                                    model.setTtTop(new DecimalFormat("0").format(top));
                                    model.setTtStart(TimeUtils.convertTimeYMD(Long.valueOf(ttStart)));
                                    model.setTtEnd(TimeUtils.convertTimeYMD(Long.valueOf(ttEnd)));
                                    data.add(model);
                                }
//                                TODO 需换成真实数据名称
//                                mAdapter.setData(data);
                                mAdapter.notifyDataSetChanged();
                            } else {
                                mListView.setVisibility(View.GONE);
                            }
                            //商品列表
                            JSONArray product = jsonObject.getJSONArray("product");
                            System.out.println("----------------------zhixing");
                            if (product.length() > 0) {
                                System.out.println("--------zhixing");
                                goodsData.clear();
                                for (int i = 0; i < product.length(); i++) {
                                    JSONObject temp = product.getJSONObject(i);
                                    GoodsModel model = new GoodsModel();
                                    String tpId = temp.getString("tpId");
                                    String name = temp.getString("tpName");
                                    String price = temp.getString("tpSalePrice");
                                    String redBag = temp.getString("tpRedCount");
                                    String photo = temp.getString("tpPic");
                                    if (photo.contains(",")) {
                                        String pic = photo.substring(0, photo.indexOf(","));
                                        model.setGoodsPhoto(pic);
                                    } else {
                                        model.setGoodsPhoto(photo);
                                    }
                                    model.setGoodsName(name);
                                    model.setGoodsPrice(price);
                                    model.setRedBagCount(redBag);
                                    model.setTpId(tpId);
                                    goodsData.add(model);
                                }
                                goodsAdapter.setData(goodsData);
                                goodsAdapter.notifyDataSetChanged();

                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                showMsg("当前网络不可用，请检查网络");
            }
        });
    }

    //优惠券
    public void getTicket() {
        String tmId = SPHelper.getTmId();
        //String ttId = SPHelper.getTtId();
        RequestParams params = new RequestParams();
        params.addBodyParameter("tmId", tmId);
        params.addBodyParameter("ttId", ttId);
        Log.e(TAG, "ttid=" + ttId);
        Log.e(TAG, "tmID=" + tmId);
        loadData(HttpRequest.HttpMethod.POST, ApiDefine.GET_TICKET, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> response) {
                Log.v(TAG, "onSuccess response.result  "
                        + response.result);
                if (TextUtils.isEmpty(response.result)) {
                  ToastUtilsCenter.makeText(context, "抱歉，领取失败", false).show();
                } else {
                    try {
                        JSONObject jsonObject = new JSONObject(response.result);
                        String code = jsonObject.getString("code");
                        if (code.equalsIgnoreCase("100")) {
                           ToastUtilsCenter.makeText(context, "恭喜，领取成功", true).show();
                        } else if (code.equalsIgnoreCase("101")) {
                          ToastUtilsCenter.makeText(context, "抱歉，领取失败", false).show();
                        } else if (code.equalsIgnoreCase("104")) {
                            ToastUtilsCenter.makeText(context, "已领取，不能重复领取", false).show();
                    }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
            }
        });
    }

    @Override
    public void onClick(View view) {

    }

    @Override
    protected void onResume() {
        scrollView.smoothScrollTo(0, 0);
        super.onResume();
    }
}
